import {Divider, Popconfirm, Input, message, Row, Col, Form, Select, Card, Button, InputNumber} from 'antd'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import {connect} from 'umi'
import {addSecurityUser, deleteEmployeeSecurity, getItemBySecurityId, addDisabledOrLargerInfo} from '../../service'
import {employeeStatusList, formatTypeList} from "@/utils/constant";

const FormItem = Form.Item;
const {Option} = Select;

const TableForm = ({addUserList, securityInfo, securityUserItems, tableToolbarRender}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState([]);
  const [fixedAmountData, setFixedAmountData] = useState({});
  const [largerMedicalData, setLargerMedicalData] = useState({});
  const [disabledEmploymentData, setDisabledEmploymentData] = useState({});
  const [selectedRowsData, setSelectedRowsData] = useState([]);
  const [showFlag,setShowFlag] = useState({
    showPension : true,
    showInjuryInsurance : true,
    showLargerMedical : false,
    showMedicalInsurance : true,
    showUnemploymentInsurance : true,
    showMaternityInsurance : true,
    showDisabledEmployment : false
  });

  let columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      disabled: true,
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      disabled: true
    },
    {
      title: '公司',
      dataIndex: 'orgname',
      key: 'orgname',
      disabled: true
    },
    {
      title: '状态',
      dataIndex: 'employeestatus',
      key: 'employeestatus',
      disabled: true,
      render: (text,record) =>{
        return text!=='-' ? employeeStatusList.find(item => (item.value===text)).label : ''
      }
    },
    {
      title: '养老保险基数',
      dataIndex: 'endowmentInsurance',
      key: 'endowmentInsurance',
      hideInTable: showFlag.showPension,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.endowmentInsurance} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'endowmentInsurance', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '失业保险基数 ',
      dataIndex: 'unemploymentInsurance',
      key: 'unemploymentInsurance',
      hideInTable: showFlag.showUnemploymentInsurance,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.unemploymentInsurance} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'unemploymentInsurance', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '医疗保险基数',
      dataIndex: 'medicalInsurance',
      key: 'medicalInsurance',
      hideInTable: showFlag.showMedicalInsurance,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.medicalInsurance} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'medicalInsurance', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '工伤保险基数',
      dataIndex: 'injuryInsurance',
      key: 'injuryInsurance',
      hideInTable: showFlag.showInjuryInsurance,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.injuryInsurance} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'injuryInsurance', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '大额医疗',
      dataIndex: 'largerMedical',
      key: 'largerMedical',
      hideInTable: !showFlag.showLargerMedical,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.largerMedical} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'largerMedical', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '生育保险基数 ',
      dataIndex: 'maternityInsurance',
      key: 'maternityInsurance',
      hideInTable: showFlag.showMaternityInsurance,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.maternityInsurance} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'maternityInsurance', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '残疾保障金基数 ',
      dataIndex: 'disabledEmployment',
      key: 'disabledEmployment',
      hideInTable: !showFlag.showDisabledEmployment,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input disabled={fixedAmountData.disabledEmployment} value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'disabledEmployment', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '150px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="删除此行会产生异动记录，是否删除？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ];

  useEffect(()=>{
    getItemBySecurityId(securityInfo.typeId).then(res =>{
      let flag = {...showFlag};
      if (res){
        let fixedAmountObj = {};
        res.forEach((item,index) =>{
          if (item.securityType === 0){
            flag.showPension = false;
            fixedAmountObj.endowmentInsurance = item.personalFixedAmount;
          }else if (item.securityType === 1){
            flag.showUnemploymentInsurance = false;
            fixedAmountObj.unemploymentInsurance = item.personalFixedAmount;
          }else if (item.securityType === 2){
            flag.showMedicalInsurance = false;
            fixedAmountObj.medicalInsurance = item.personalFixedAmount;
          }else if (item.securityType === 3){
            flag.showInjuryInsurance = false;
            fixedAmountObj.injuryInsurance = item.personalFixedAmount;
          }else if (item.securityType === 4){
            flag.showLargerMedical = true;
            fixedAmountObj.largerMedical = item.personalFixedAmount;
          }else if (item.securityType === 7){
            flag.showMaternityInsurance = false;
            fixedAmountObj.maternityInsurance = item.personalFixedAmount;
          }else if (item.securityType === 8){
            flag.showDisabledEmployment = true;
            fixedAmountObj.disabledEmployment = item.personalFixedAmount;
          }
        });
        setFixedAmountData(fixedAmountObj);
        setShowFlag(flag);
      }
    });
    },[securityInfo]);

  useEffect(() => {
    setLoading(true);
    if (securityUserItems.length > 0) {
      setData(
        securityUserItems.map((item, index) => {
          return {key: 'had' + index, ...item, ...securityInfo};
        })
      );
    }
    if (addUserList.length > 0) {
      let newData = [...data];
      for (let i = 0; i < addUserList.length; i++) {
        let isContinue = false;
        for (let a = 0; a < data.length; a++) {
          if (data[a].oid === addUserList[i].oid) {
            isContinue = true;
          }
        }
        if (isContinue)
          continue;
        newData.push({
          key: addUserList[i].oid,
          id: null,
          code: addUserList[i].code,
          employeestatus: addUserList[i].employeestatus,
          oid: addUserList[i].oid,
          name: addUserList[i].name,
          orgname: addUserList[i].orgname,
          ...securityInfo,
          ...fixedAmountData,
        });
      }
      setData(newData);
    }

    setLoading(false);
  }, [addUserList,securityUserItems]);

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0]

  const toggleEditable = (e, key, record) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      if (record){
        target.id = record.id;
        target.endowmentInsurance = record.endowmentInsurance;
        target.injuryInsurance = record.injuryInsurance;
        target.largerMedical = record.largerMedical;
        target.medicalInsurance = record.medicalInsurance;
        target.unemploymentInsurance = record.unemploymentInsurance;
        target.maternityInsurance = record.maternityInsurance;
        target.disabledEmployment = record.disabledEmployment;
      }
      setData(newData)
    }
  };

  const remove = (e, record) => {
    setLoading(true);
    const newData = [...data];
    if (record.id){
      deleteEmployeeSecurity(record.id, securityInfo.typeId, securityInfo.type, record.oid).then(res => {
        if (res.flag){
          message.success('社保方案人员删除成功！');
          let datas = newData.filter(item => item.key !== record.key);
          setData(datas)
        }else {
          message.error(res.error);
        }
        setLoading(false);
      });
    }else {
      let datas = newData.filter(item => item.key !== record.key);
      setData(datas);
      setLoading(false);
    }
  }

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data]
    const target = getRowByKey(key, newData)
    if (target) {
      target[fieldName] = e.target ? e.target.value : e
      setData(newData)
    }
  }

  const updateRow = (e, rowKey, oid) => {
    setLoading(true);
    e.persist()
    if (clickedCancel) {
      setClickedCancel(false)
      return
    }
    const target = getRowByKey(rowKey) || {};
    addSecurityUser(target).then(res =>{
      if (res.flag){
        toggleEditable(e, rowKey, res.data);
        message.success('社保方案人员绑定成功！');
      }else {
        message.error(res.error);
      }
      setLoading(false);
    })
  }

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...item, ...cacheOriginData[key], editable: false};
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    setData(cacheData);
    setClickedCancel(false)
  };

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowsData(selectedRows);
    },
  };

  const oneTimePayment = (type) => {
    if (selectedRowsData.length<1){
      message.error('请先选择缴纳人员');
      return;
    }
    let oids = [];
    selectedRowsData.forEach(item=>{
      if (!item.id){
        message.error(`${item.name}未保存，请保存后再试！`);
        return;
      }
      oids.push(item.oid);
    });
    let initParams = {oids: oids, securityId: securityInfo.typeId};
    let restParams;
    if (type===4){
      restParams = {...largerMedicalData, type: type};
    }else if (type===8){
      restParams = {...disabledEmploymentData, type: type}
    }
    addDisabledOrLargerInfo({...initParams,...restParams}).then(res =>{
      if (res.flag){
        message.success('缴纳成功');
      }else {
        message.error(res.error);
      }
    })
  };

  const oneTimePaymentChange = (e, key, type) => {
    let finalData;
    if (type===4){
      finalData = {...largerMedicalData};
      finalData[key] = e;
      setLargerMedicalData(finalData);
    }else if (type===8){
      finalData = {...disabledEmploymentData};
      finalData[key] = e;
      setDisabledEmploymentData(finalData);
    }
  };

  return (
    <>
      <Row gutter={24} style={{marginBottom: 20}}>
        {
          !showFlag.showLargerMedical && <Col span={12}>
            <Card title="大额医疗缴纳">
              <Row gutter={24}>
                <div style={{display:'flex',minWidth: '250px',alignItems:'center',margin:'10px 10px'}}>
                  <div style={{width:'110px'}}>个人缴纳：</div>
                  <InputNumber placeholder="请输入" onChange={(e)=>oneTimePaymentChange(e,'amountPerson',4)}/>
                </div>
                <div style={{display:'flex',minWidth: '250px',alignItems:'center',margin:'10px 10px'}}>
                  <div style={{width:'110px'}}>公司缴纳：</div>
                  <InputNumber placeholder="请输入" onChange={(e)=>oneTimePaymentChange(e,'amountOrg',4)}/>
                </div>
                <Button type="primary" style={{margin:'10px 10px'}} onClick={() => oneTimePayment(4)}>提交</Button>
              </Row>
            </Card>
          </Col>
        }
        {
          !showFlag.showDisabledEmployment && <Col span={12}>
            <Card title="残疾保障金缴纳">
              <Row gutter={24}>
                <div style={{display:'flex',minWidth: '250px',alignItems:'center',margin:'10px 10px'}}>
                  <div style={{width:'110px'}}>个人缴纳：</div>
                  <InputNumber placeholder="请输入" onChange={(e)=>oneTimePaymentChange(e,'amountPerson',8)}/>
                </div>
                <div style={{display:'flex',minWidth: '250px',alignItems:'center',margin:'10px 10px'}}>
                  <div style={{width:'110px'}}>公司缴纳：</div>
                  <InputNumber placeholder="请输入" onChange={(e)=>oneTimePaymentChange(e,'amountOrg',8)}/>
                </div>
                <Button type="primary" style={{margin:'10px 10px'}} onClick={() => oneTimePayment(8)}>提交</Button>
              </Row>
            </Card>
          </Col>
        }
      </Row>

      <ProTable
        loading={loading}
        columns={columns}
        dataSource={data}
        toolBarRender={tableToolbarRender}
        search={false}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
        rowSelection={{
          type: 'checkbox',
          ...rowSelection,
        }}
      />

    </>
  )
}

export default connect(({recruitment}) => ({
  recruitment,
}))(TableForm)

